package com.ruoyi.monitor.infoprojectmonitor.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.monitor.infoprojectmonitor.domain.InfoProjectMonitor;
import com.ruoyi.monitor.infoprojectmonitor.service.IInfoProjectMonitorService;
import com.ruoyi.monitor.infoprojectmonitor.vo.InfoProjectMonitorListVo;
import com.ruoyi.monitor.infoprojectmonitor.vo.ProjectMonitorVo;
import com.ruoyi.monitor.infoprojectmonitorrelation.domain.InfoProjectMonitorRelation;
import com.ruoyi.monitor.infoprojectmonitorrelation.service.IInfoProjectMonitorRelationService;
import com.ruoyi.monitor.infoprojectmonitorrelation.vo.InfoProjectMonitorDetailVo;
import com.ruoyi.system.service.ISysRoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;

import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 项目监控Controller
 *
 * @author ruoyi
 * @date 2022-02-14
 */
@RestController
@RequestMapping("/infoProjectMonitor/infoProjectMonitor")
public class InfoProjectMonitorController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(InfoProjectMonitorController.class);
    @Autowired
    private IInfoProjectMonitorService infoProjectMonitorService;
    @Autowired
    private IInfoProjectMonitorRelationService infoProjectMonitorRelationService;
    @Resource
    private ISysRoleService sysRoleService;

    /**
     * 处室查询接口
     * 查询项目监控 处室 列表
     */
    @PreAuthorize("@ss.hasPermi('infoProjectMonitor:infoProjectMonitor:list')")
    @GetMapping("/list")
    public TableDataInfo list(InfoProjectMonitor infoProjectMonitor) {
        long begin = System.currentTimeMillis();
        List<InfoProjectMonitorListVo> result = new ArrayList<>();
        //判断如果是主管处室只查询当前处室的项目，如果角色是审计处，则查询全部
        Long userId=SecurityUtils.getUserId();
        List<SysRole> roles=sysRoleService.selectRolesByUserIdList(userId);
        Optional.ofNullable(roles).orElseThrow(() -> new RuntimeException("该登录用户没有角色信息！"));
        List<String> rileKeys=roles.stream().map(SysRole::getRoleKey).collect(Collectors.toList());
        List<InfoProjectMonitor> list=new ArrayList<>();
        if(rileKeys.contains("sjc")){
            /*infoProjectMonitor.setDeptId(SecurityUtils.getDeptId());*/
            startPage();
            list = infoProjectMonitorService.selectInfoProjectMonitorList(infoProjectMonitor);
        }else{
            //项目监控 所在处室只能查询自己的
            infoProjectMonitor.setDepartmentId(SecurityUtils.getDeptId());
            startPage();
            list = infoProjectMonitorService.selectInfoProjectMonitorList(infoProjectMonitor);
        }
        for (InfoProjectMonitor projectMonitor : list) {
            InfoProjectMonitorListVo listVo = new InfoProjectMonitorListVo();
            listVo.setInfoProjectMonitor(projectMonitor);
            //查询下达项数据
            List<InfoProjectMonitorRelation> infoProjectMonitorRelations = infoProjectMonitorRelationService.selectProjectMonitorRelationListByProjectId(projectMonitor.getId());
            listVo.setInfoProjectMonitorRelations(infoProjectMonitorRelations);
            result.add(listVo);
        }
        TableDataInfo dataTable = getDataTable(list);
        dataTable.setRows(result);
        long timeValue = System.currentTimeMillis() - begin;
        log.info("查询项目监控数据信息耗时:" + TimeUnit.MILLISECONDS.toSeconds(timeValue) + "秒");
        return dataTable;
    }


    /**
     * 导出项目监控列表
     */
    @PreAuthorize("@ss.hasPermi('infoProjectMonitor:infoProjectMonitor:export')")
    @Log(title = "项目监控", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, InfoProjectMonitor infoProjectMonitor) {
        List<InfoProjectMonitor> list = infoProjectMonitorService.selectInfoProjectMonitorList(infoProjectMonitor);
        ExcelUtil<InfoProjectMonitor> util = new ExcelUtil<InfoProjectMonitor>(InfoProjectMonitor.class);
        util.exportExcel(response, list, "项目监控数据");
    }

    /**
     * 获取项目监控详细信息
     */
    @PreAuthorize("@ss.hasPermi('infoProjectMonitor:infoProjectMonitor:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(infoProjectMonitorService.selectInfoProjectMonitorById(id));
    }

    /**
     * 新增项目监控
     */
    @PreAuthorize("@ss.hasPermi('infoProjectMonitor:infoProjectMonitor:add')")
    @Log(title = "项目监控", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody InfoProjectMonitor infoProjectMonitor) {
        return toAjax(infoProjectMonitorService.insertInfoProjectMonitor(infoProjectMonitor));
    }

    /**
     * 修改项目监控
     */
    @PreAuthorize("@ss.hasPermi('infoProjectMonitor:infoProjectMonitor:edit')")
    @Log(title = "项目监控", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody InfoProjectMonitor infoProjectMonitor) {
        return toAjax(infoProjectMonitorService.updateInfoProjectMonitor(infoProjectMonitor));
    }

    /**
     * 删除项目监控
     */
    @PreAuthorize("@ss.hasPermi('infoProjectMonitor:infoProjectMonitor:remove')")
    @Log(title = "项目监控", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(infoProjectMonitorService.deleteInfoProjectMonitorByIds(ids));
    }

    /**
     * 项目监控下达
     *
     * @param projectMonitorVo
     * @return
     */
    @RequestMapping(value = "/reportProjectMonitor", method = RequestMethod.POST)
    public AjaxResult reportProjectMonitor(@RequestBody ProjectMonitorVo projectMonitorVo) {
        return toAjax(infoProjectMonitorService.reportProjectMonitor(projectMonitorVo));
    }

    /**
     * 项目监控批量下达
     *
     * @param json
     * @return
     */
    @PostMapping("reportProjectMonitorBatch")
    public AjaxResult reportProjectMonitorBatch(@RequestBody JSONObject json) {
        JSONArray jsonArray =json.getJSONArray("secondProjectIds");
        Optional.ofNullable(jsonArray).orElseThrow(() -> new RuntimeException("未获取到项目信息！"));
        List<Long> projectIds=jsonArray.toJavaList(Long.class);
        String monitorTime=json.getString("monitorTime");
        Optional.ofNullable(monitorTime).orElseThrow(() -> new RuntimeException("未获取到监控周期！"));
        String remark=json.getString("remark");
        infoProjectMonitorService.reportProjectMonitorBatch(projectIds,monitorTime,remark);
        return AjaxResult.success("批量下达成功！");
    }

    /**
     * 获取监控项目详情 不含指标列表
     *
     * @param projectMonitorId
     * @return
     */
    @RequestMapping(value = "/getProjectMonitorDetail", method = RequestMethod.GET)
    public AjaxResult getProjectMonitorDetail(@RequestParam("projectMonitorId") Long projectMonitorId) {
        InfoProjectMonitorDetailVo detailVo = infoProjectMonitorService.getProjectMonitorDetail(projectMonitorId);
        return AjaxResult.success(detailVo);
    }

}
